package org.colafries.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.colafries.admin.service.IBaseService;
import org.colafries.admin.wrapper.Response;
import org.colafries.admin.wrapper.ResponseWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author Ann
 * @version v1.0
 * @ClassName BaseController
 * @Description
 * @date Created in 2024/6/7
 **/
public abstract class BaseController<S extends IBaseService<T, V>, T, V> {

    @Autowired
    private ApplicationContext applicationContext;

    S service;

    @PostConstruct
    public void init() {
        String serviceName = getServiceName();
        this.service = (S) applicationContext.getBean(serviceName);
    }

    protected abstract String getServiceName();

    /**
     * listAll method
     *
     * @param v
     * @return org.colafries.admin.wrapper.Response<?>
     * @Author anning
     * @Date 2024/6/7
     */
    @PostMapping("/listAll")
    public Response<?> listAll(@RequestBody V v) {
        List<T> result = service.listAll(v);
        return ResponseWrapper.ok(result);
    }

    /**
     * add method
     *
     * @param v
     * @return org.colafries.admin.wrapper.Response<?>
     * @Author anning
     * @Date 2024/6/7
     */
    @PostMapping("/add")
    public Response<?> add(@RequestBody V v) {
        int result = service.add(v);
        return ResponseWrapper.ok(result);
    }

    /**
     * update method
     *
     * @param v
     * @return org.colafries.admin.wrapper.Response<?>
     * @Author anning
     * @Date 2024/6/7
     */
    @PostMapping("/update")
    public Response<?> update(@RequestBody V v) {
        int result = service.update(v);
        return ResponseWrapper.ok(result);
    }

    /**
     * delete method
     *
     * @param v
     * @return org.colafries.admin.wrapper.Response<?>
     * @Author anning
     * @Date 2024/6/7
     */
    @PostMapping("/delete")
    public Response<?> delete(@RequestBody V v) {
        int result = service.delete(v);
        return ResponseWrapper.ok(result);
    }

    @PostMapping("/pageList")
    public Response<?> pageList(@RequestBody V v) {
        IPage<T> result = service.pageList(v);
        return ResponseWrapper.ok(result);
    }
}
